<template>
  <div class='user'>
    <!-- 输入框 -->
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input v-model="SearchUserVo.username" placeholder="请输入用户名"></el-input>
      </el-col>
      <el-col :span="4">
        <el-input v-model="SearchUserVo.loginAccount" placeholder="请输入登录账号"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="SearchUserVo.type" placeholder="请选择用户类型">
          <el-option v-for="item in userType" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="SearchUserVo.status" placeholder="请选择账号状态">
          <el-option v-for="item in userStatus" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4" style="text-align: left">
        <el-button type="primary" @click="searchUserByConditions(true)" icon="el-icon-search">查询</el-button>
      </el-col>
      <el-col :span="4" style="text-align: right">
        <el-button type="primary" @click="addUserVisible = true" icon="el-icon-plus">添加用户</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table :data="userList" style="width: 100%" height="550" border stripe>
      <el-table-column type="index" width="50" align="center" label="序号">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100" align="center">
      </el-table-column>
      <el-table-column prop="loginAccount" label="登录账号" width="120" align="center">
      </el-table-column>
      <el-table-column prop="status" label="账号状态" width="100" align="center">
      </el-table-column>
      <el-table-column prop="type" label="用户类型" width="100" align="center">
      </el-table-column>
      <el-table-column prop="createUser" label="创建人" width="100" align="center">
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="180" align="center">
      </el-table-column>
      <el-table-column prop="updateUser" label="修改人" width="100" align="center">
      </el-table-column>
      <el-table-column prop="updateDate" label="修改时间" width="180" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="240" align="center">
        <template slot-scope="scope">
          <el-button @click="checkUser(scope.row.id)" type="text" size="mini" style="color: #67c23a"><i class="el-icon-view"></i>&nbsp;查看</el-button>
          <el-button type="text" @click="getUserById(scope.row.id)" size="mini" style="color: #409eff"><i class="el-icon-edit"></i>&nbsp;编辑</el-button>
          <el-button type="text" @click="getIdForEdit(scope.row.id)" size="mini" style="color: #909399"><i class="el-icon-lock"></i>&nbsp;修改密码</el-button>
          <el-button type="text" @click="delUser(scope.row.id)" size="mini" style="color: #f56c6c"><i class="el-icon-delete"></i>&nbsp;删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[15, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper" :total="dataSize" align="center">
    </el-pagination>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addUserVisible" width="36%" :before-close="cancelAddUser">
      <el-form ref="addForm" :model="UserBasic" :rules="AddUserRules" label-width="100px" label-position="left" style="margin: 20px 40px;">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="UserBasic.username" style="width: 280px;" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="登录账号:" prop="loginAccount">
          <el-input v-model="UserBasic.loginAccount" style="width: 280px;" placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="UserBasic.password" style="width: 280px;" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="用户状态:" prop="status">
          <el-select v-model="UserBasic.status" placeholder="请选择用户状态" style="width: 280px;">
            <el-option v-for="item in userStatus" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型:" prop="type">
          <el-select v-model="UserBasic.type" placeholder="请选择用户类型" style="width: 280px;">
            <el-option v-for="item in userType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div style="margin-top: 40px"></div>
        <el-form-item>
          <el-button type="primary" @click="AddUser">保存</el-button>
          <el-button style="margin-left: 80px;" @click="cancelAddUser">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看用户信息 -->
    <el-dialog title="用户信息" :visible.sync="checkUserVisible" :before-close="cancelCheckUser">
      <el-descriptions column="1" border>
        <el-descriptions-item label="用户名">{{ UserBasicDto.username }}</el-descriptions-item>
        <el-descriptions-item label="登录账号">{{ UserBasicDto.loginAccount }}</el-descriptions-item>
        <el-descriptions-item label="账号状态">{{ changeStatus(UserBasicDto.status) }}</el-descriptions-item>
        <el-descriptions-item label="用户类型">{{ changeType(UserBasicDto.type) }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ UserBasicDto.createUser }}</el-descriptions-item>
        <el-descriptions-item label="修改人">{{ UserBasicDto.updateUser }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ UserBasicDto.createDate }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ UserBasicDto.updateDate }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!-- 编辑用户信息 -->
    <el-dialog title="编辑用户" :visible.sync="editUserVisible" width="36%" :before-close="canceleditUser">
      <el-form ref="form" :model="UserBasic" :rules="AddUserRules" label-width="100px" label-position="left" style="margin: 20px 40px;">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="UserBasic.username" style="width: 280px;" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="登录账号:" prop="loginAccount">
          <el-input v-model="UserBasic.loginAccount" style="width: 280px;" placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <el-form-item label="用户状态:" prop="status">
          <el-select v-model="UserBasic.status" placeholder="请选择用户状态" style="width: 280px;">
            <el-option v-for="item in userStatus" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型:" prop="type">
          <el-select v-model="UserBasic.type" placeholder="请选择用户类型" style="width: 280px;">
            <el-option v-for="item in userType" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div style="margin-top: 40px"></div>
        <el-form-item>
          <el-button type="primary" @click="editUser">保存</el-button>
          <el-button style="margin-left: 80px;" @click="canceleditUser">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog title="修改密码" :visible.sync="editPasswordVisible" width="35%" :before-close="cancelEditPassword">
      <el-form ref="form" :model="UserBasic" label-width="80px" :rules="AddUserRules" label-position="left" style="margin: 20px 40px;">
        <el-form-item label="密码:" prop="password">
          <el-input v-model="UserBasic.password" style="width: 280px;" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <div style="margin-top: 40px"></div>
        <el-form-item>
          <el-button type="primary" @click="editPassword">保存</el-button>
          <el-button style="margin-left: 80px;" @click="cancelEditPassword">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'

export default {
  name: 'UserIndex',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
  // 这里存放数据
    return {
      baseUser: '/user-basic',
      // 页码
      pageIndex: 1,
      // 每页页数
      pageSize: 15,
      dataSize: 0,
      // 添加用户表单显示状态
      addUserVisible: false,
      // 查看用户详细信息显示状态
      checkUserVisible: false,
      // 编辑用户表单显示状态
      editUserVisible: false,
      // 修改密码表单显示状态
      editPasswordVisible: false,
      // 用户类型
      userType: [
        {
          value: 1,
          label: '用户'
        },
        {
          value: 2,
          label: '员工'
        },
        {
          value: 3,
          label: '管理员'
        },
        {
          value: 4,
          label: '超级管理员'
        }
      ],
      // 用户账户状态
      userStatus: [
        {
          value: 1,
          label: '启用'
        },
        {
          value: 2,
          label: '禁用'
        }
      ],
      // 查询用户参数对象
      SearchUserVo: {
        username: '',
        loginAccount: '',
        type: '',
        status: ''
      },
      userList: [],
      UserBasicDto: {
        id: 0,
        username: '',
        loginAccount: '',
        password: '',
        status: '',
        type: '',
        createUser: '',
        createDate: new Date(),
        updateUser: '',
        updateDate: new Date(),
        isDeleted: false
      },
      UserBasic: {
        id: 0,
        username: '',
        loginAccount: '',
        password: '',
        status: '',
        type: '',
        createUser: 0,
        // createDate: new Date(),
        updateUser: 0,
        // updateDate: new Date(),
        isDeleted: false
      },
      AddUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, message: '长度在 不得小于 3 个字符', trigger: 'blur' }
        ],
        loginAccount: [
          { required: true, message: '请输入登录账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {
  },
  // 监控data中的数据变化
  watch: {
    userList: {
      deep: true,
      immediate: true,
      handler (newUserList) {
        newUserList = newUserList.forEach(itemList => {
          itemList.status = this.changeStatus(itemList.status)
          itemList.type = this.changeType(itemList.type)
          return itemList
        })
      }
    }
  },
  // 方法集合
  methods: {
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    // 根据条件查询用户列表
    searchUserByConditions (flag) {
      this.SearchUserVo.status = this.SearchUserVo.status === '' ? 0 : this.SearchUserVo.status
      this.SearchUserVo.type = this.SearchUserVo.type === '' ? 0 : this.SearchUserVo.type
      // 执行查询操作
      request({
        url: this.baseUser + `/user-list/${this.pageIndex}/${this.pageSize}`,
        method: 'get',
        params: this.SearchUserVo
      }).then(result => {
        if (result.data.data.data != null) {
          this.userList = result.data.data.data
          this.dataSize = result.data.data.size
          if (flag) {
            // 查询成功后弹出信息
            this.$message({
              message: '查询成功',
              type: 'success'
            })
          }
          // 查询成功后清空默认数据
          this.SearchUserVo = {}
        } else {
          // 查询失败后弹出信息
          this.$message({
            message: '查询失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '查询失败',
          type: 'error'
        })
        console.log(error)
      })
    },
    // 添加用户
    AddUser () {
      // 执行添加用户操作
      request({
        url: this.baseUser + '/user-basic',
        method: 'post',
        data: this.UserBasic
      }).then(result => {
        if (result.data.data) {
          // 添加成功后隐藏添加弹窗
          this.addUserVisible = false
          // 添加成功后弹出提示消息
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          // 添加成功后清除默认数据
          this.UserBasic = {}
          // 添加成功后刷新界面
          this.searchUserByConditions()
        } else {
          // 添加失败后弹出提示消息
          this.$message({
            message: '添加失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '添加失败',
          type: 'error'
        })
        console.log(error)
      })
    },
    // 取消添加用户
    cancelAddUser () {
      this.addUserVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    // 查看用户
    checkUser (id) {
      this.checkUserVisible = true
      // 查看用户操作
      request({
        url: this.baseUser + `/user-basic/${id}`,
        method: 'get'
      }).then(result => {
        if (result.data.data != null) {
          // 查看用户操作成功操作
          this.UserBasicDto = result.data.data
          // this.$message({
          //   message: '查看成功',
          //   type: 'success'
          // })
        } else {
          // 查看用户操作失败操作
          this.$message({
            message: '查看失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '查看失败',
          type: 'error'
        })
        console.log(error)
      })
      // 根据id请求用户数据
    },
    // 取消查看用户
    cancelCheckUser () {
      this.checkUserVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    /**
     * 编辑用户
     */
    // 1.回显用户信息
    getUserById (id) {
      this.editUserVisible = true
      // 回显用户操作
      request({
        url: this.baseUser + `/user-basic/${id}`,
        method: 'get'
      }).then(result => {
        if (result.data.data != null) {
          // 查看用户操作成功操作
          const { id, username, loginAccount, status, type } = result.data.data
          this.UserBasic = { id, username, loginAccount, status, type }
        } else {
          // 查看用户操作失败操作
          this.$message({
            message: '用户回显失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '用户回显失败',
          type: 'error'
        })
        console.log(error)
      })
    },
    // 2.修改用户
    editUser () {
      // 修改用户
      request({
        url: this.baseUser + '/user-basic',
        method: 'put',
        data: this.UserBasic
      }).then(result => {
        if (result.data.data) {
          // 修改用户成功操作
          this.editUserVisible = false
          // 修改成功后弹出提示消息
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          // 修改成功后清除默认数据
          this.UserBasic = {}
          // 修改成功后刷新界面
          this.searchUserByConditions()
        } else {
          // 修改失败后弹出提示消息
          this.$message({
            message: '编辑失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '编辑失败',
          type: 'error'
        })
        console.log(error)
      })
    },
    // 取消修改用户
    canceleditUser () {
      this.editUserVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
      // 取消修改后清除默认数据
      this.UserBasic = {}
    },
    /**
     * 修改密码
     */
    // 1.获取要修改的用户id
    getIdForEdit (id) {
      this.editPasswordVisible = true
      this.UserBasic.id = id
    },
    // 2.修改密码
    editPassword () {
      this.UserBasic.status = this.UserBasic.status === '' ? 0 : this.UserBasic.status
      this.UserBasic.type = this.UserBasic.type === '' ? 0 : this.UserBasic.type
      this.editPasswordVisible = false
      // 修改密码操作
      request({
        url: this.baseUser + '/user-basic',
        method: 'put',
        data: this.UserBasic
      }).then(result => {
        if (result.data.data) {
          // 修改密码成功操作
          this.editUserVisible = false
          // 修改密码成功后弹出提示消息
          this.$message({
            message: '密码修改成功',
            type: 'success'
          })
          // 修改成功后清除默认数据
          this.UserBasic = {}
        } else {
          // 修改失败后弹出提示消息
          this.$message({
            message: '密码修改失败',
            type: 'error'
          })
        }
      }).catch(error => {
        this.$message({
          message: '密码修改失败',
          type: 'error'
        })
        console.log(error)
      })
    },
    // 取消修改密码
    cancelEditPassword () {
      this.editPasswordVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    // 删除用户
    delUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除用户操作
        request({
          url: this.baseUser + `/user-basic/${id}`,
          method: 'delete'
        }).then(result => {
          // 删除成功后执行操作
          if (result.data.data) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 删除成功后刷新界面
            this.searchUserByConditions()
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        }).catch(error => {
          this.$message({
            message: '删除失败',
            type: 'error'
          })
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 查看用户时根据status的值动态修改为对应字符串
    changeStatus (status) {
      this.userStatus.forEach(item => {
        if (item.value === status) status = item.label
      })
      return status
    },
    // 查看用户时根据type的值动态修改为对应字符串
    changeType (type) {
      this.userType.forEach(item => {
        if (item.value === type) {
          type = item.label
        }
      })
      return type
    },
    // 每页数据数变化
    handleSizeChange (val) {
      this.pageSize = val
      // 分页查询
      this.loading = true
      this.searchUserByConditions()
    },
    // 当前处于哪一页
    handleCurrentChange (val) {
      this.pageIndex = val
      // 分页查询
      this.loading = true
      this.searchUserByConditions()
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.searchUserByConditions()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  // 生命周期 - 更新之后
  updated () {
  },
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
  .user {
    background-color: #fff;
    height: 690px;
    padding: 20px 20px;
    border-radius: 30px;
  }
  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
  }

  .el-table .warning-row {
    background: rgb(154, 108, 23);
  }

  .el-table .success-row {
    background: #429217;
  }
</style>
